package com.megvii.corelib.update.service;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.view.WindowManager;

import com.megvii.corelib.base.MegviiActivity;
import com.megvii.corelib.update.UpdateManager;
import com.megvii.corelib.update.UpdateUtil;
import com.megvii.corelib.update.activity.UpdateActivity;
import com.megvii.corelib.update.param.UpdateActivityParam;
import com.megvii.corelib.update.param.UpdateServiceParam;
import com.megvii.corelib.update.task.UpdateErrorCode;

import java.io.File;

import de.greenrobot.event.EventBus;

/**
 * Created by linyue on 16/3/6.
 */
public class UpdateService extends Service implements UpdateManager.UpdateManagerListener
{
    public static final String EXTRA_KEY = "EXTRA_KEY";

    private UpdateManager updateManager;

    private NotificationManager notificationManager;

    private Notification notification;

    private PendingIntent pendingIntent;

    private UpdateServiceParam param;

    private UpdateActivityParam activityParam;

    private int lastProgress = -1;

    @Override
    public void onCreate()
    {
        super.onCreate();
        updateManager = new UpdateManager();
        updateManager.init();
        updateManager.registerListener(this);
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        updateManager.release();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        if (intent != null)
        {
            param = (UpdateServiceParam) intent.getSerializableExtra(EXTRA_KEY);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return new UpdateServiceBinder(this, updateManager);
    }

    public void setActivityParam(UpdateActivityParam activityParam)
    {
        this.activityParam = activityParam;
    }

    @Override
    public void onGetSpaceNeeded(String urlString, String fileName, int size)
    {
        if (UpdateUtil.isSpaceEnough(size))
        {
            updateManager.downloadAPK(urlString, fileName);
        }
        else
        {
            alertError(UpdateErrorCode.SPACE_NOT_ENOUGH);
        }
    }

    @Override
    public void onDownloadStart()
    {
        if (param != null)
        {
            notification = new Notification(param.notifyIconId, "自动更新正在进行",
                    System.currentTimeMillis());
            Intent notificationIntent = new Intent(this, UpdateActivity.class);
            notificationIntent.putExtra(MegviiActivity.KEY_ACTIVITY_PARAM, activityParam);
            pendingIntent = PendingIntent
                    .getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
        lastProgress = -1;
    }

    @Override
    public void onDownloadProgress(int progress)
    {
        if (notification != null)
        {
            if (lastProgress != progress)
            {
                notification
                        .setLatestEventInfo(this, param.notifyTitle, progress + "%", pendingIntent);
                startForeground(1, notification);
                lastProgress = progress;
            }
        }
    }

    @Override
    public void onDownloadCompleted(String fileName)
    {
        //启动安装程序
        File file = UpdateUtil.getFile(fileName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
        stopForeground(true);
    }

    @Override
    public void onDownloadError(String url, String fileName, int errorCode)
    {
        if (errorCode == UpdateErrorCode.NETWORK_DISCONNECT)
        {
            updateManager.downloadAPK(url, fileName);
        }
        else
        {
            alertError(errorCode);
        }
    }

    @Override
    public void onDownloadInterrupt()
    {

    }

    private void alertError(int errorCode)
    {
        String message = "未知错误" + errorCode;
        switch (errorCode)
        {
            case UpdateErrorCode.NO_PERMISSION_TO_WRITE_FILE:
                message = "没有权限写入文件";
                break;
            case UpdateErrorCode.SPACE_NOT_ENOUGH:
                message = "系统空间不足，请清理后重试";
                break;
            case UpdateErrorCode.NETWORK_DISCONNECT:
                message = "网络错误";
                break;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("自动更新失败");
        builder.setMessage(message);
        builder.setPositiveButton("确定", null);
        AlertDialog dialog = builder.create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    public class UpdateServiceBinder extends Binder
    {
        public UpdateService service;

        public UpdateManager updateManager;

        public UpdateServiceBinder(UpdateService service, UpdateManager updateManager)
        {
            super();
            this.service = service;
            this.updateManager = updateManager;
        }
    }
}
